package com.xxh.dasongapp.security.config.filter;
import com.xxh.dasongapp.security.config.WxAppletAuthenticationToken;
import com.xxh.dasongapp.security.utils.JwtUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    @Qualifier("userNameDetailServiceImpl")
    UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader(JwtUtil.getHeader());

        //token为空
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //token在有效时间之内
        if(!JwtUtil.isTokenExpired(token)){
            //todo 使用redis进行缓存
            String username = JwtUtil.getUsername(token);
            String openId = JwtUtil.getOpenId(token);
            //openid无绑定账户时，username为空
            if (username != null){
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(userToken);
            }else {
                WxAppletAuthenticationToken wxAuthenticationToken = new WxAppletAuthenticationToken(openId);
                SecurityContextHolder.getContext().setAuthentication(wxAuthenticationToken);
            }


        }


        //放行
        filterChain.doFilter(request,response);
    }
}
